<template>
  <!-- <div> -->
  <!-- 遮罩阻止点击别的按钮 -->
  <div v-if="visible" class="custom-dialog-big-background">
    <!-- 自定义弹窗 -->
    <div class="custom-dialog">
      <div class="dialog-backdrop" @click="closeDialog"></div>

      <div class="dialog-container">
        <div class="dialog-header">
          <slot name="header">
            <h3 class="dialog-title">{{ title }}</h3>
          </slot>
          <div class="buttons">
            <img src="../assets/img/module5/dialog/guanbi.png" @click="closeDialog" alt="关闭" class="button-icon" />
          </div>
        </div>

        <div class="dialog-content">
          <div v-if="step === 1" class="step-container">
            <h4 class="step-title">Step1: 请选择空域使用需求数据</h4> <!-- Step 1 标题 -->
            <div class="table-container">
              <div class="table-left">
                <h4>待选择的数据：</h4>

                <!-- 🔥 新增：筛选区域（月份+关键词+搜索按钮） -->
                <div class="filter-container">
                  <!-- 月份选择器 -->
                  <el-date-picker v-model="selectedMonth" type="month" placeholder="选择筛选月份" value-format="yyyy-MM"
                    style="width: 150px; margin-right: 15px;" :disabled-date="disableFutureMonth"></el-date-picker>
                  <!-- 关键词搜索框（可选） -->
                  <el-input v-model="userName" placeholder="请输入用户名" style="width: 175px; margin-right: 15px;"
                    clearable></el-input>
                  <!-- 搜索按钮 -->
                  <el-button type="primary" @click="fetchTableData" icon="el-icon-search">搜索</el-button>
                </div>

                <el-table ref="multipleTable1" :data="tableData1" tooltip-effect="dark" class="container-scoll"
                  style="width: 100%; height: 300px; overflow: auto;" @selection-change="handleSelectionChange1">
                  <el-table-column type="selection" width="55"></el-table-column>
                  <el-table-column label="用户名" prop="userName" width="150"></el-table-column>
                  <el-table-column label="接收时间" prop="applicationAcceptanceTime"></el-table-column>
                </el-table>
              </div>

              <!-- 中间的按钮 -->
              <div class="button-container">
                <div class="button-group">
                  <img src="@/assets/img/module2/rightArrow.png" @click="addToRight1" alt="添加选中数据"
                    class="button-image" />
                </div>
                <div class="clear-button-container">
                  <img src="@/assets/img/module2/leftArrow.png" @click="clearSelection1" alt="清除选中"
                    class="button-image" />
                </div>
              </div>


              <!-- 第一类数据的右侧表格 -->
              <div class="table-right">
                <h4>已选择的数据：</h4>
                <el-table ref="multipleTableRight1" :data="selectedRowsRight1" class="container-scoll"
                  style="width: 100%; height: 300px; overflow: auto; margin-top: 87px;" @selection-change="handleSelectionChangeRight1">
                  <el-table-column type="selection" width="55"></el-table-column>
                  <el-table-column label="用户名" prop="userName" width="150"></el-table-column>
                  <el-table-column label="接收时间" prop="applicationAcceptanceTime"></el-table-column>
                </el-table>
              </div>
            </div>
          </div>

          <!-- <div v-if="step === 2" class="step-container">
            <h4 class="step-title">Step2: 请选择空域使用规范数据</h4>
            <div class="table-container">
              <div class="table-left">
                <h4>待选择的数据：</h4>
                <el-table ref="multipleTable2" :data="tableData2" tooltip-effect="dark" class="container-scoll"
                  style="width: 100%; height: 300px; overflow: auto;" @selection-change="handleSelectionChange2">
                  <el-table-column type="selection" width="55" show-overflow-tooltip></el-table-column>
                  <el-table-column label="文件名称" prop="title" width="150" show-overflow-tooltip></el-table-column>
                  <el-table-column label="信息类别" prop="informationCategory" show-overflow-tooltip></el-table-column>
                </el-table>
              </div>

              <div class="button-container">
                <div class="button-group">
                  <img src="@/assets/img/module2/rightArrow.png" @click="addToRight2" alt="添加选中数据"
                    class="button-image" />
                </div>
                <div class="clear-button-container">
                  <img src="@/assets/img/module2/leftArrow.png" @click="clearSelection2" alt="清除选中"
                    class="button-image" />
                </div>
              </div>

              <div class="table-right">
                <h4>已选择的数据：</h4>
                <el-table ref="multipleTableRight2" :data="selectedRowsRight2" class="container-scoll"
                  style="width: 100%; height: 300px; overflow: auto;" @selection-change="handleSelectionChangeRight2">
                  <el-table-column type="selection" width="55"></el-table-column>
                  <el-table-column label="文件名称" prop="title" width="150" show-overflow-tooltip></el-table-column>
                  <el-table-column label="信息类别" prop="informationCategory" show-overflow-tooltip></el-table-column>
                </el-table>
              </div>
            </div>
          </div> -->
          <!-- 🔥 Step2 202509核心修改：空域使用分析维度（固定4个选项） -->
          <div v-if="step === 2" class="step-container">
            <h4 class="step-title">Step2: 请选择空域使用分析维度</h4> <!-- 标题修改 -->
            <div class="table-container">
              <div class="table-left">
                <h4>待选择的分析维度：</h4>
                <!-- 左侧表格：固定4个分析维度，支持表头全选/单选 -->
                <el-table ref="multipleTable2" :data="tableData2" tooltip-effect="dark" class="container-scoll"
                  style="width: 100%; height: 300px; overflow: auto;" @selection-change="handleSelectionChange2">
                  <el-table-column type="selection" width="100" show-overflow-tooltip></el-table-column>
                  <el-table-column label="分析维度" prop="title" show-overflow-tooltip></el-table-column>
                </el-table>
              </div>

              <div class="button-container">
                <div class="button-group">
                  <img src="@/assets/img/module2/rightArrow.png" @click="addToRight2" alt="添加选中维度"
                    class="button-image" />
                </div>
                <div class="clear-button-container">
                  <img src="@/assets/img/module2/leftArrow.png" @click="clearSelection2" alt="清除选中维度"
                    class="button-image" />
                </div>
              </div>

              <!-- 右侧表格：已选分析维度 -->
              <div class="table-right">
                <h4>已选择的分析维度：</h4>
                <el-table ref="multipleTableRight2" :data="selectedRowsRight2" class="container-scoll"
                  style="width: 100%; height: 300px; overflow: auto;" @selection-change="handleSelectionChangeRight2">
                  <el-table-column type="selection" width="100"></el-table-column>
                  <el-table-column label="已选分析维度" prop="title" show-overflow-tooltip></el-table-column>
                </el-table>
              </div>
            </div>
          </div>

          <div class="buttonWapper">
            <button class="diaButton" @click="closeDialog">取消</button>
            <button class="diaButton" @click="goBackStep" v-if="step === 2">上一步</button>
            <button class="diaButton" @click="nextStep" v-if="step === 1">下一步</button>
            <button class="diaButton" @click="confirmDialog" v-if="step === 2">生成方案</button>
          </div>
        </div>

        <div class="dialog-footer">
          <img src="../assets/img/module5/dialog/dialogicon3.png" class="img-foot" />
        </div>
      </div>
    </div>
  </div>
  <!-- </div> -->
</template>

<script>
import axios from 'axios';

const baseApi = process.env.NODE_ENV === 'production'
  //? process.env.VUE_APP_REMOTE_API
  ? '/api'  // 使用代理路径
  : process.env.VUE_APP_REMOTE_API_MODULE2;


export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    title: {
      type: String,
      default: "新增空域方案", // 弹窗默认标题
    },
    closeButtonText: {
      type: String,
      default: "关闭", // 关闭按钮默认文本
    },
    width: {
      type: String,
      default: '600px'
    },
    height: {
      type: String,
      default: '300px'
    },
  },
  data() {
    return {
      step: 1,  // 当前步骤
      tableData1: [],  // 用来存储从后端获取的数据,
      // tableData2: [],
      tableData2: [
        { id: 1, title: '任务类型匹配' },
        { id: 2, title: '碰撞风险评估' },
        { id: 3, title: '空域间距评估' },
        { id: 4, title: '时间冲突评估' }
      ],
      // 筛选相关变量
      selectedMonth: '',
      userName: null,  // 初始化为空字符串
      order: '时间最新',
      selectedRowsRight1: [],  // 第一步选中的数据（右侧显示的数据）
      selectedRowsRight2: [],  // 第二步选中的数据（右侧显示的数据）
      RowsRight1Selected: [],  // 第一步选（右侧被选中的数据）
      RowsRight2Selected: [],  // 第二步选（右侧被选中的数据）
      selectedRows1: [],  // 第一张表格选中的数据
      selectedRows2: [],  // 第二张表格选中的数据
    };
  },
  mounted() {
    // this.initDefaultMonth();
    this.fetchTableData();
    // this.fetchAirspaceNormsAndConstraints();
  },
  methods: {
    // 初始化默认月份为当前月份
    initDefaultMonth() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补0（1→01）
      this.selectedMonth = `${year}-${month}`;
    },

    // 禁用未来月份选择（可选：避免选择未到的月份）
    disableFutureMonth(date) {
      return date > new Date();
    },

    // 🔥 核心：请求后端数据（带筛选参数）
    async fetchTableData() {
      // 显示加载中（表格数据加载）
      const loading = this.$loading({
        target: '.table-left .container-scoll',
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.5)'
      });

      try {
        // 1. 构建请求参数（严格匹配后端要求格式）
        const requestParams = {
          currentPage: 1,
          size: 20,
          // 若userName为空或仅空格，则传递null
          userName: (this.userName || '').trim() || null,
          order: this.order,
          // 初始值设为null而非空字符串
          startTime: null,
          endTime: null
        };

        // 2. 处理月份筛选：转换为 startTime/endTime（当月1日0点 → 下月1日0点）
        if (this.selectedMonth) {
          const [year, month] = this.selectedMonth.split('-').map(Number);
          // 当月第一天 00:00:00（如：2025-09-01T00:00:00）
          const startDate = new Date(year, month - 1, 1);
          // 下月第一天 00:00:00（如：2025-10-01T00:00:00）
          const endDate = new Date(year, month, 1);

          // 格式化为后端要求的字符串，只有选择了月份才赋值
          requestParams.startTime = this.formatDateToISO(startDate);
          requestParams.endTime = this.formatDateToISO(endDate);
        }
        // 未选择月份时，startTime和endTime保持为null

        // console.log('请求后端筛选参数:', requestParams);
        // 3. 发送POST请求（参数放在请求体中）
        const response = await axios.post(
          `${baseApi}/admin/airspaceDemand/keywordSearch`,
          requestParams // POST请求的data参数（后端接收的请求体）
        );

        // 4. 处理后端返回数据
        const rawData = response.data?.data?.pageData || [];
        if (rawData.length === 0) {
          this.$message.info('未查询到符合条件的数据');
          this.tableData1 = [];
          return;
        }

        // 5. 过滤并格式化数据（只保留待审核/审核中）
        this.tableData1 = rawData
          .filter(item => item.approvalStatus === 0 || item.approvalStatus === 3)
          .map((item, index) => ({
            id: index + 1,          // 表格序号
            userName: item.userName || '未知用户',
            applicationAcceptanceTime: item.applicationReceiveTime
              ? new Date(item.applicationReceiveTime).toLocaleString()
              : '未知时间',
            approvalStatus: item.approvalStatus === 0 ? '待审核' : '审核中',
            originalId: item.id     // 保留后端原始ID（后续操作可能需要）
          }));

      } catch (error) {
        console.error("数据请求失败:", error);
        this.$message.error("数据加载失败，请重试");
        this.tableData1 = [];
      } finally {
        // 关闭加载
        loading.close();
      }
    },

    // 辅助：日期转换为 "yyyy-MM-dd'T'HH:mm:ss" 格式
    formatDateToISO(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}T00:00:00`;
    },
    // async fetchTableData() {
    //   try {
    //     // 请求参数，你可以根据实际需求调整
    //     const params = {
    //       currentPage: 1,
    //       size: 20,
    //     };

    //     const response = await axios.post(`${baseApi}/admin/airspaceDemand/keywordSearch`, params);
    //     console.log("add弹窗从后端获取到的用户需求数据", response)

    //     const rawData = response.data.data.pageData;

    //     // ✅ 只保留 approvalStatus 为 0（待审核）或 3（审核中）
    //     const filteredData = rawData.filter(item => item.approvalStatus === 0 || item.approvalStatus === 3);

    //     this.tableData1 = filteredData.map((item, index) => ({
    //       id: index + 1,
    //       userName: item.userName,
    //       applicationAcceptanceTime: new Date(item.applicationReceiveTime).toLocaleString(),
    //       approvalStatus: item.approvalStatus === 0 ? '待审核' : '审核通过',
    //     }));
    //   } catch (error) {
    //     console.error("数据请求失败:", error);
    //     this.$message.error("数据加载失败");
    //   }
    // },
    async fetchAirspaceNormsAndConstraints() {
      try {
        const params = {
          currentPage: 1,
          size: 20,
        };

        const response = await axios.post(`${baseApi}/admin/airspaceNormsAndConstraints/keywordSearch`, params);
        // 处理返回的数据
        const convertedData = response.data.data.pageData.map((item, index) => {
          return {
            // 保留文件名称和信息类别字段
            id: index + 1,  // 序号
            title: item.title,  // 文件名称
            informationCategory: item.informationCategory === 1 ? '通知公告' :
              (item.informationCategory === 0 ? '政策法规' : '未知'),  // 信息类别
          };
        });

        this.tableData2 = convertedData;  // 将处理后的数据赋值给 tableData2

      } catch (error) {
        console.error("请求数据失败", error);
      }
    },
    closeDialog() {
      this.$emit("update:visible", false); // 通知父组件关闭弹窗
    },
    handleSelectionChange1(val) {
      this.selectedRows1 = val;
    },
    handleSelectionChange2(val) {
      this.selectedRows2 = val;
    },
    handleSelectionChangeRight1(val) {
      this.RowsRight1Selected = val;
    },
    handleSelectionChangeRight2(val) {
      this.RowsRight2Selected = val;
    },
    addToRight1() {
      if (this.selectedRows1.length === 0) {
        this.$message.error('请至少选择一行数据');
        return;
      }
      // 避免重复添加
      this.selectedRows1.forEach(row => {
        if (!this.selectedRowsRight1.some(existingRow => existingRow.id === row.id)) {
          this.selectedRowsRight1.push(row);
        }
      });
    },
    addToRight2() {
      if (this.selectedRows2.length === 0) {
        this.$message.error('请至少选择一行数据');
        return;
      }
      // 避免重复添加
      this.selectedRows2.forEach(row => {
        if (!this.selectedRowsRight2.some(existingRow => existingRow.id === row.id)) {
          this.selectedRowsRight2.push(row);
        }
      });
    },
    clearSelection1() {
      // 仅清除右侧表格的选中项
      const table1 = this.$refs.multipleTable1;
      const tableRight1 = this.$refs.multipleTableRight1;

      this.RowsRight1Selected.forEach(row => {
        // 取消左侧表格中对应数据的选中状态
        const leftRow = this.tableData1.find(item => item.id === row.id);
        const rightRow = this.selectedRowsRight1.find(item => item.id === row.id);
        if (leftRow) {
          table1.toggleRowSelection(leftRow, false);
        }
        if (rightRow) {
          tableRight1.toggleRowSelection(rightRow, false);  // 取消右侧表格中的选中状态
          // 从 selectedRowsRight1 数组中移除该项
          const index = this.selectedRowsRight1.indexOf(rightRow);
          if (index !== -1) {
            this.selectedRowsRight1.splice(index, 1);  // 从数组中移除
          }
        }
      });
      // 清空右侧选中的数据
      this.RowsRight1Selected = [];
    },
    clearSelection2() {
      // 仅清除右侧表格的选中项
      const table2 = this.$refs.multipleTable2;
      const tableRight2 = this.$refs.multipleTableRight2;

      this.RowsRight2Selected.forEach(row => {
        // 取消左侧表格中对应数据的选中状态
        const leftRow = this.tableData2.find(item => item.id === row.id);
        const rightRow = this.selectedRowsRight2.find(item => item.id === row.id);
        if (leftRow) {
          table2.toggleRowSelection(leftRow, false);
          tableRight2.toggleRowSelection(rightRow, false);  // 取消选中
        }
        if (rightRow) {
          tableRight2.toggleRowSelection(rightRow, false);  // 取消选中
          // 从 selectedRowsRight2 数组中移除该项
          const index = this.selectedRowsRight2.indexOf(rightRow);
          if (index !== -1) {
            this.selectedRowsRight2.splice(index, 1);  // 从数组中移除
          }
        }
      });
      // 清空右侧选中的数据
      this.RowsRight2Selected = [];
    },
    // 上一步按钮的点击处理方法
    goBackStep() {
      this.step = 1; // 切换到第一步
    },
    nextStep() {
      if (this.selectedRowsRight1.length === 0) {
        this.$message.error('请至少选择一行数据');
        return;
      }
      this.step = 2; // 切换到第二步
    },
    confirmDialog() {
      if (this.selectedRowsRight2.length === 0) {
        this.$message.error('请至少选择一行数据');
        return;
      }
      // 打印所有选中的数据
      console.log('选中的数据 (第一步):', this.selectedRowsRight1);
      console.log('选中的数据 (第二步):', this.selectedRowsRight2);

      // ✅ 1. 使用 this.$loading 开启全屏遮罩
      const loadingInstance = this.$loading({
        lock: true,
        text: '智能算法正在生成空域方案...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      // ✅ 2. 模拟请求
      setTimeout(() => {
        loadingInstance.close(); // ✅ 3. 操作完成关闭 loading

        this.$message.success('方案生成成功');
        this.closeDialog();
        this.$emit('refresh-data'); // 通知父组件刷新
      }, 2000);
    },
  },
};
</script>



<style scoped>
/* 筛选容器样式 */
.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 8px 0;
}

/* 适配Element UI组件样式 */
::v-deep .el-date-picker__input,
::v-deep .el-input__inner {
  background-color: rgba(0, 0, 0, 0.3);
  border-color: rgba(255, 255, 255, 0.2);
  color: white;
}

::v-deep .el-date-picker__placeholder,
::v-deep .el-input__placeholder {
  color: rgba(255, 255, 255, 0.6);
}

::v-deep .el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

::v-deep .el-button--primary:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}


.custom-dialog-big-background {
  position: fixed;
  top: 0%;
  left: 0%;
  width: 100%;
  height: 100%;
  /* background-color: transparent; */
  background-color: rgba(0, 0, 0, 0.6);
  /* 半透明的黑色背景 */
  z-index: 99;
}

/* 弹窗背景 */
.custom-dialog {
  position: fixed;
  top: 50%;
  left: 55%;
  width: 50vw;
  height: 50vh;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9998;
}


.dialog-container {
  position: relative;
  width: 100%;
  background-image: url("../assets/img/module5/dialog/container.png");
  background-size: cover;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-radius: 10px;
  /* 圆角设置 */
}

.dialog-header {
  display: flex;
  width: 100%;
  height: 3rem;
  justify-content: center;
  align-items: center;
  position: relative;
  background-image: url("../assets/img/module5/dialog/headbar.png"), url("../assets/img/module5/dialog/dialogtopimg1.png"), url("../assets/img/module5/dialog/dialogtopimg2.png");
  background-position: center, center, center;
  background-size: cover, auto, cover;
  background-repeat: no-repeat, no-repeat, no-repeat;
  border-top-left-radius: 10px;
  /* 左上角圆角 */
  border-top-right-radius: 10px;
  /* 右上角圆角 */
}

.dialog-title {
  font-size: 1.5rem;
  color: #ffffff;
  text-align: center;
  margin: 0;
}

.buttons {
  position: absolute;
  right: 2%;
}

.button-icon {
  width: 40px;
  height: 40px;
  cursor: pointer;
}

.dialog-content {
  width: 100%;
  margin-top: 1rem;
  margin-bottom: 1rem;
  padding: 0 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

/* 主要新增或修改部分在此 */

.step-title {
  font-size: 1.2rem;
  color: white;
  margin: 0;
}

.table-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.table-left,
.table-right {
  width: 42%;
}

.table-right h4,
.table-left h4 {
  color: white;
}

.button-container {
  display: flex;
  flex-direction: column;
  /* 使按钮在垂直方向排列 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
  /* 水平居中 */
  gap: 10px;
  /* 按钮之间的间隔 */
}

.button-group,
.clear-button-container {
  display: flex;
  margin-top: 2rem;
  justify-content: center;
  /* 居中按钮 */
  align-items: center;
}

.button-image {
  width: 30px;
  /* 设置图片宽度，可以根据实际情况调整 */
  height: auto;
  /* 根据宽度自动调整高度 */
  cursor: pointer;
  /* 鼠标悬停时显示手型光标 */
}

.buttonWapper {
  display: flex;
  justify-content: center;
  gap: 20px;
  width: 100%;
  margin-top: 2rem;
  position: auto;
}

.diaButton {
  height: 30px;
  width: 120px;
  border: none;
  color: white;
  font-size: 18px;
  background-color: transparent;
  background-image: url('../assets/img/module2/button-tijiao.png');
  background-size: 100% 100%;
  cursor: pointer;
}

.diaButton:hover {
  background-color: rgba(255, 255, 255, 0.1);
  transform: scale(1.05);
}

/* 弹窗底部 */
.dialog-footer {
  display: flex;
  width: 100%;
  height: 2rem;
  margin-bottom: 1rem;
  position: relative;
}

/*右下角标识*/
.img-foot {
  position: absolute;
  right: 2%;
}

/* 修改 show-overflow-tooltip 的 z-index */
::v-deep .el-tooltip__popper {
  z-index: 9999;
  /* 根据需要设置一个较高的 z-index */
}

.container-scoll::-webkit-scrollbar {
  width: 2px;
}

.container-scoll::-webkit-scrollbar {
  background-color: rgba(0, 16, 29, 0.5) !important;
}

.container-scoll::-webkit-scrollbar-thumb {
  background: #0378FF;
  border-radius: 10px;
}
</style>